<template>
  <div class="intelligent-welcome h-screen w-screen overflow-hidden relative" :style="{
    background: 'var(--gradient-primary)',
    color: 'var(--color-textPrimary)'
  }">
    <!-- 动态背景粒子效果 -->
    <div class="absolute inset-0 overflow-hidden">
      <div 
        v-for="i in 50" 
        :key="i"
        class="absolute rounded-full"
        :style="Object.assign({
          backgroundColor: 'var(--color-accent)',
          opacity: 0.2
        }, getParticleStyle(i))"
      ></div>
    </div>

    <!-- 主要内容区域 -->
    <div class="relative z-10 h-full flex overflow-hidden">
      <!-- 左侧机器人欢迎区域 -->
      <div class="flex-1 flex items-center justify-center min-w-0">
        <div class="text-center">
          <!-- 小旦机器人 -->
          <div class="relative mb-8">
            <IntelligentRobot
              :robot-name="'小旦智能管家'"
              :is-active="true"
              :is-speaking="isSpeaking"
              :is-thinking="isThinking"
              :is-excited="isExcited"
              :status="robotStatus"
            />
          </div>

          <!-- 动态欢迎文字 -->
          <div class="mb-8">
            <h1 class="text-4xl font-bold mb-4 animate-fade-in">{{ currentWelcomeText }}</h1>
            <p class="text-xl animate-fade-in-delay" :style="{ color: 'var(--color-accent)' }">{{ currentSubText }}</p>
          </div>

          <!-- 语音波纹效果 -->
          <div v-if="isSpeaking" class="flex justify-center space-x-1 mb-8">
            <div 
              v-for="i in 5" 
              :key="i"
              class="w-1 rounded-full animate-pulse"
              :style="{
                backgroundColor: 'var(--color-accent)',
                height: `${20 + Math.random() * 30}px`,
                animationDelay: `${i * 0.1}s`
              }"
            ></div>
          </div>

          <!-- 快速入口按钮 -->
          <div class="flex justify-center space-x-4">
            <button @click="startConversation" class="cyber-button px-8 py-3 text-lg">
              开始对话
            </button>
            <button @click="skipWelcome" class="border px-8 py-3 rounded-xl transition-all"
              :style="{
                borderColor: 'var(--color-border)',
                color: 'var(--color-textPrimary)',
                backgroundColor: 'transparent'
              }"
              @mouseover="hoverButton = true"
              @mouseleave="hoverButton = false"
            >
              直接进入
            </button>
          </div>
        </div>
      </div>

      <!-- 右侧智能推荐标签区域 -->
      <div class="w-96 min-w-[384px] p-6 flex-shrink-0" :style="{
        backgroundColor: 'var(--color-glassBg)',
        borderLeft: '1px solid var(--color-border)',
        backdropFilter: 'blur(12px)'
      }">
        <div class="h-full flex flex-col">
          <!-- 标题 -->
          <div class="mb-6">
            <h2 class="text-2xl font-bold text-white mb-2 flex items-center">
              <Sparkles class="w-6 h-6 mr-2 text-electric-500" />
              智能推荐
            </h2>
            <p class="text-white/70">基于您的需求智能匹配</p>
          </div>

          <!-- 用户画像快览 -->
          <div class="mb-6 p-4 rounded-xl" :style="{
            backgroundColor: 'var(--color-surface)',
            border: '1px solid var(--color-border)'
          }">
            <h3 :style="{ color: 'var(--color-textPrimary)' }" class="font-medium mb-3 flex items-center">
              <User class="w-4 h-4 mr-2" />
              用户画像
            </h3>
            <div class="grid grid-cols-2 gap-2 text-sm">
              <div :style="{ color: 'var(--color-textSecondary)' }">
                <span :style="{ color: 'var(--color-accent)' }">行业：</span>{{ userProfile.industry }}
              </div>
              <div :style="{ color: 'var(--color-textSecondary)' }">
                <span :style="{ color: 'var(--color-accent)' }">规模：</span>{{ userProfile.scale }}
              </div>
              <div :style="{ color: 'var(--color-textSecondary)' }">
                <span :style="{ color: 'var(--color-accent)' }">地区：</span>{{ userProfile.region }}
              </div>
              <div :style="{ color: 'var(--color-textSecondary)' }">
                <span :style="{ color: 'var(--color-accent)' }">关注：</span>{{ userProfile.focus }}
              </div>
            </div>
          </div>

          <!-- 智能标签推荐 -->
          <div class="flex-1">
            <h3 class="text-white font-medium mb-4 flex items-center">
              <Target class="w-4 h-4 mr-2 text-electric-500" />
              今日推荐 ({{ recommendedTags.length }})
            </h3>
            
            <div class="space-y-3 max-h-80 overflow-y-auto scrollbar-thin scrollbar-thumb-electric-500/50 scrollbar-track-white/10">
              <div
                v-for="(tag, index) in recommendedTags"
                :key="tag.id"
                :class="[
                  'group p-4 rounded-xl border-2 cursor-pointer transition-all duration-300',
                  'hover:scale-105 hover:shadow-lg transform',
                  tag.priority === 'high' ? 'border-red-500/50 bg-red-500/10' :
                  tag.priority === 'medium' ? 'border-yellow-500/50 bg-yellow-500/10' :
                  'border-electric-500/50 bg-electric-500/10'
                ]"
                @click="selectTag(tag)"
                :style="{ animationDelay: `${index * 0.1}s` }"
              >
                <div class="flex items-start justify-between">
                  <div class="flex-1">
                    <div class="flex items-center mb-2">
                      <span class="text-2xl mr-3">{{ tag.icon }}</span>
                      <div>
                        <h4 class="text-white font-medium">{{ tag.title }}</h4>
                        <p class="text-white/60 text-sm">{{ tag.description }}</p>
                      </div>
                    </div>
                    
                    <div class="flex items-center justify-between mt-3">
                      <div class="flex items-center space-x-2">
                        <span :class="[
                          'px-2 py-1 rounded-full text-xs font-medium',
                          tag.priority === 'high' ? 'bg-red-500/20 text-red-400' :
                          tag.priority === 'medium' ? 'bg-yellow-500/20 text-yellow-400' :
                          'bg-green-500/20 text-green-400'
                        ]">
                          {{ tag.priorityText }}
                        </span>
                        <span class="text-electric-500 text-xs">
                          匹配度: {{ tag.matchScore }}%
                        </span>
                      </div>
                      
                      <ChevronRight class="w-4 h-4 text-white/40 group-hover:text-electric-500 transition-colors" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 底部操作区 -->
          <div class="mt-6 pt-4 border-t border-white/10">
            <button 
              @click="refreshRecommendations"
              class="w-full cyber-button py-3 mb-3 relative z-50"
            >
              <RefreshCw class="w-4 h-4 mr-2" />
              刷新推荐
            </button>
            <button 
              @click="customizePreferences"
              class="w-full border border-white/30 text-white py-3 rounded-xl hover:bg-white/10 transition-all relative z-50"
            >
              <Settings class="w-4 h-4 mr-2 inline" />
              偏好设置
            </button>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载动画 -->
    <div 
      v-if="isLoading"
      class="absolute inset-0 bg-black/50 backdrop-blur-sm flex items-center justify-center z-50"
    >
      <div class="text-center">
        <div class="w-16 h-16 border-4 border-electric-500 border-t-transparent rounded-full animate-spin mb-4"></div>
        <p class="text-white text-lg">{{ loadingText }}</p>
      </div>
    </div>

    <!-- 偏好设置弹窗 -->
    <div 
      v-if="showPreferences"
      class="fixed inset-0 bg-black/70 backdrop-blur-md flex items-center justify-center z-[100]"
      @click="showPreferences = false"
    >
      <div 
        class="bg-cyber-900/95 backdrop-blur-md border border-electric-500/30 rounded-2xl p-8 max-w-md w-full mx-4 shadow-2xl"
        @click.stop
      >
        <div class="flex justify-between items-center mb-6">
          <h3 class="text-2xl font-bold text-white flex items-center">
            <Settings class="w-6 h-6 mr-3 text-electric-500" />
            偏好设置
          </h3>
          <button 
            @click="showPreferences = false"
            class="text-white/60 hover:text-white transition-colors"
          >
            <span class="text-2xl">&times;</span>
          </button>
        </div>
        
        <div class="space-y-6">
          <!-- 行业偏好 -->
          <div>
            <label class="block text-white font-medium mb-3">行业偏好</label>
            <select 
              v-model="userProfile.industry"
              class="w-full cyber-input"
            >
              <option value="制造业">制造业</option>
              <option value="电商">电商</option>
              <option value="科技">科技</option>
              <option value="金融">金融</option>
              <option value="教育">教育</option>
            </select>
          </div>
          
          <!-- 企业规模 -->
          <div>
            <label class="block text-white font-medium mb-3">企业规模</label>
            <select 
              v-model="userProfile.scale"
              class="w-full cyber-input"
            >
              <option value="小微企业">小微企业</option>
              <option value="中型企业">中型企业</option>
              <option value="大型企业">大型企业</option>
            </select>
          </div>
          
          <!-- 关注重点 -->
          <div>
            <label class="block text-white font-medium mb-3">关注重点</label>
            <select 
              v-model="userProfile.focus"
              class="w-full cyber-input"
            >
              <option value="税收优惠">税收优惠</option>
              <option value="补贴申请">补贴申请</option>
              <option value="政策解读">政策解读</option>
              <option value="合规指导">合规指导</option>
            </select>
          </div>
          
          <!-- 推送频率 -->
          <div>
            <label class="block text-white font-medium mb-3">推送频率</label>
            <div class="grid grid-cols-3 gap-2">
              <button 
                v-for="freq in ['实时', '每日', '每周']" 
                :key="freq"
                @click="pushFrequency = freq"
                :class="[
                  'py-2 px-3 rounded-lg text-sm transition-all',
                  pushFrequency === freq 
                    ? 'bg-electric-500 text-white' 
                    : 'bg-white/10 text-white/70 hover:bg-white/20'
                ]"
              >
                {{ freq }}
              </button>
            </div>
          </div>
        </div>
        
        <div class="flex space-x-3 mt-8">
          <button 
            @click="savePreferences"
            class="flex-1 cyber-button py-3"
          >
            保存设置
          </button>
          <button 
            @click="showPreferences = false"
            class="flex-1 border border-white/30 text-white py-3 rounded-xl hover:bg-white/10 transition-all"
          >
            取消
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { 
  Sparkles, 
  User, 
  Target, 
  ChevronRight, 
  RefreshCw, 
  Settings 
} from 'lucide-vue-next'
import { useTranslation } from '../composables/useTranslation.js'
import IntelligentRobot from '../components/IntelligentRobot.vue'

export default {
  name: 'IntelligentWelcome',
  components: {
    Sparkles,
    User,
    Target,
    ChevronRight,
    RefreshCw,
    Settings,
    IntelligentRobot
  },
  setup() {
    const { ts } = useTranslation()
    return { ts }
  },
  data() {
    return {
      isWelcoming: true,
      isThinking: false,
      isExcited: false,
      isSpeaking: false,
      isLoading: false,
      loadingText: '',
      robotStatus: 'online',
      showPreferences: false,
      pushFrequency: '实时',
      
      // 欢迎文字动画
      welcomeTexts: [
        '欢迎来到跨境政策咨询平台！',
        '我是小旦，您的专属智能管家',
        '让我为您提供个性化服务',
        '准备好开始您的智能之旅了吗？'
      ],
      subTexts: [
        '基于大模型的智能政策分析与推荐系统',
        '我将根据您的需求提供精准的政策匹配',
        '个性化推荐、智能分析、实时更新',
        '点击右侧标签开始探索您关心的内容'
      ],
      currentWelcomeIndex: 0,
      
      // 用户画像数据
      userProfile: {
        industry: '制造业',
        scale: '中型企业',
        region: '华东地区',
        focus: '税收优惠'
      },
      
      // 智能推荐标签
      recommendedTags: [
        {
          id: 1,
          icon: '🎯',
          title: '跨境电商税收政策',
          description: '基于您的行业特征推荐',
          priority: 'high',
          priorityText: '紧急',
          matchScore: 95,
          module: 'policy-search',
          params: { category: 'cross-border-ecommerce' }
        },
        {
          id: 2,
          icon: '💰',
          title: '制造业数字化补贴',
          description: '符合您企业规模的优惠政策',
          priority: 'high',
          priorityText: '推荐',
          matchScore: 88,
          module: 'subsidy-application',
          params: { type: 'digital-transformation' }
        },
        {
          id: 3,
          icon: '🏢',
          title: '小微企业扶持政策',
          description: '最新优惠政策汇总',
          priority: 'medium',
          priorityText: '关注',
          matchScore: 82,
          module: 'enterprise-support',
          params: { scale: 'small-medium' }
        },
        {
          id: 4,
          icon: '📊',
          title: 'AI智能咨询',
          description: '专业政策问题解答',
          priority: 'normal',
          priorityText: '推荐',
          matchScore: 76,
          module: 'ai-chat',
          params: {}
        },
        {
          id: 5,
          icon: '🎓',
          title: '博士后政策专区',
          description: '人才引进相关政策',
          priority: 'normal',
          priorityText: '可选',
          matchScore: 65,
          module: 'talent-policy',
          params: { type: 'postdoc' }
        }
      ]
    }
  },
  computed: {
    currentWelcomeText() {
      return this.welcomeTexts[this.currentWelcomeIndex] || this.welcomeTexts[0]
    },
    currentSubText() {
      return this.subTexts[this.currentWelcomeIndex] || this.subTexts[0]
    }
  },
  methods: {
    getParticleStyle(index) {
      const size = Math.random() * 4 + 2
      const duration = Math.random() * 20 + 10
      const delay = Math.random() * 5
      return {
        width: `${size}px`,
        height: `${size}px`,
        left: `${Math.random() * 100}%`,
        top: `${Math.random() * 100}%`,
        animation: `float ${duration}s ${delay}s infinite linear`
      }
    },
    
    startConversation() {
      this.isSpeaking = true
      this.isExcited = true
      
      setTimeout(() => {
        this.navigateToModule('ai-chat')
      }, 1000)
    },
    
    skipWelcome() {
      this.$router.push('/dashboard')
    },
    
    selectTag(tag) {
      this.isLoading = true
      this.loadingText = `正在进入${tag.title}...`
      
      // 模拟加载
      setTimeout(() => {
        this.navigateToModule(tag.module, tag.params)
      }, 1500)
    },
    
    navigateToModule(module, params = {}) {
      const routes = {
        'policy-search': '/policy-search',
        'subsidy-application': '/subsidy',
        'enterprise-support': '/enterprise',
        'ai-chat': '/ai-chat',
        'talent-policy': '/talent'
      }
      
      const route = routes[module] || '/dashboard'
      this.$router.push({ path: route, query: params })
    },
    
    refreshRecommendations() {
      this.isThinking = true
      
      // 模拟AI重新分析推荐
      setTimeout(() => {
        // 随机调整匹配度和优先级
        this.recommendedTags = this.recommendedTags.map(tag => ({
          ...tag,
          matchScore: Math.max(60, Math.min(98, tag.matchScore + (Math.random() - 0.5) * 20))
        }))
        
        // 重新排序
        this.recommendedTags.sort((a, b) => b.matchScore - a.matchScore)
        
        this.isThinking = false
        this.isExcited = true
        
        setTimeout(() => {
          this.isExcited = false
        }, 2000)
      }, 2000)
    },
    
    customizePreferences() {
      // 打开偏好设置弹窗
      this.showPreferences = true
    },

    savePreferences() {
      // 保存用户偏好设置到本地存储
      const preferences = {
        userProfile: this.userProfile,
        pushFrequency: this.pushFrequency,
        lastUpdate: new Date().toISOString()
      }
      
      try {
        localStorage.setItem('userPreferences', JSON.stringify(preferences))
        console.log('偏好设置已保存:', preferences)
        
        // 触发推荐更新
        this.refreshRecommendations()
        
        // 关闭弹窗
        this.showPreferences = false
        
        // 显示成功提示
        this.showSuccessToast('偏好设置已保存！')
        
      } catch (error) {
        console.error('保存偏好设置失败:', error)
        this.showErrorToast('保存失败，请重试')
      }
    },

    showSuccessToast(message) {
      // 简单的成功提示
      this.isExcited = true
      setTimeout(() => {
        this.isExcited = false
      }, 2000)
    },

    showErrorToast(message) {
      // 简单的错误提示
      console.warn(message)
    },

    loadUserPreferences() {
      // 从本地存储加载用户偏好
      try {
        const saved = localStorage.getItem('userPreferences')
        if (saved) {
          const preferences = JSON.parse(saved)
          this.userProfile = { ...this.userProfile, ...preferences.userProfile }
          this.pushFrequency = preferences.pushFrequency || '实时'
          console.log('已加载用户偏好:', preferences)
        }
      } catch (error) {
        console.error('加载用户偏好失败:', error)
      }
    },
    
    startWelcomeAnimation() {
      // 欢迎文字轮播动画
      setInterval(() => {
        this.currentWelcomeIndex = (this.currentWelcomeIndex + 1) % this.welcomeTexts.length
      }, 3000)
      
      // 随机表情变化
      setInterval(() => {
        if (Math.random() > 0.8) {
          this.isThinking = true
          setTimeout(() => {
            this.isThinking = false
          }, 2000)
        }
      }, 5000)
      
      // 随机语音波纹
      setInterval(() => {
        if (Math.random() > 0.9) {
          this.isSpeaking = true
          setTimeout(() => {
            this.isSpeaking = false
          }, 3000)
        }
      }, 8000)
    },
    
    // 数字人播报触发（可供后续扩展）
    triggerDigitalHumanAnnouncement() {
      // 这里可以调用全局事件或直接与数字人组件通信
      this.isSpeaking = true
      setTimeout(() => {
        this.isSpeaking = false
      }, 3500)
    }
  },
  
  mounted() {
    // 加载用户偏好设置
    this.loadUserPreferences()
    
    // 启动欢迎动画
    this.startWelcomeAnimation()
    
    // 只在首次进入前端时触发数字人播报
    if (!localStorage.getItem('hasAnnouncedDigitalHuman')) {
      this.triggerDigitalHumanAnnouncement()
      localStorage.setItem('hasAnnouncedDigitalHuman', 'true')
    }
    
    // 模拟初始化过程
    setTimeout(() => {
      this.isWelcoming = false
    }, 2000)
  }
}
</script>

<style scoped>
:deep() {
  user-select: text;
  -webkit-user-select: text;
  caret-color: transparent;
  cursor: default;
}

:deep(button) {
  cursor: pointer;
}

:deep(.policy-content) {
  ::selection {
    color: inherit;
  }
}

@keyframes float {
  0%, 100% { transform: translateY(0px) rotate(0deg); }
  50% { transform: translateY(-20px) rotate(180deg); }
}

@keyframes animate-spin-slow {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

@keyframes fade-in {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

@keyframes fade-in-delay {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.animate-spin-slow {
  animation: animate-spin-slow 8s linear infinite;
}

.animate-fade-in {
  animation: fade-in 1s ease-out;
}

.animate-fade-in-delay {
  animation: fade-in-delay 1s ease-out 0.5s both;
}

/* 粒子动画 */
.intelligent-welcome::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: radial-gradient(circle at 50% 50%, rgba(0, 245, 255, 0.1) 0%, transparent 70%);
  pointer-events: none;
}

/* 自定义滚动条 */
::-webkit-scrollbar {
  width: 6px;
}

::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb {
  background: rgba(0, 245, 255, 0.5);
  border-radius: 3px;
}

::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 245, 255, 0.8);
}

/* 浅色模式下的样式覆盖 */
.theme-light .intelligent-welcome {
  background: linear-gradient(to bottom right, #f8fafc, #e0e7ef); /* 浅色背景 */
  color: #1e293b; /* 深色字体 */
}

.theme-light .text-white {
  color: #1e293b !important; /* 覆盖白色字体为深色 */
}

.theme-light .text-electric-500 {
  color: #0073e6 !important; /* 调整电光蓝为科技蓝 */
}

.theme-light .bg-black\/20 {
  background: rgba(255, 255, 255, 0.8) !important; /* 调整背景为浅色透明 */
}

.theme-light .border-electric-500\/20 {
  border-color: rgba(148, 163, 184, 0.4) !important; /* 调整边框颜色 */
}
</style> 
